#!/usr/bin/python

#if pkmisshiny:
#				shinytid,shinysid = pkmrand.shinygen(pkm[0x00:0x03])
#				pkm[0x0C:0x0D]=shinytid
#				pkm[0x0E:0x0F]=shinysid

#from resources.src.sendpkm import sendpkm as sendpokemonirgts

import pkmrand 
from pokehaxlib import *
from resources.src.pkmlib import encode
from resources.src.boxtoparty import makeparty
from sys import argv, exit
from platform import system
from base64 import urlsafe_b64encode
import os.path, resources.src.gtsvar, hashlib
try:
	from resources.src.gbatonds import makends
	bw=False
except:
	bw=True

def sendpkm():
	pkmisshiny= pkmrand.isShiny()
	if bw == False:
		token = 'c9KcX1Cry3QKS2Ai7yxL6QiQGeBGeQKR'
		
		path = pkmrand.genpathIV()

		path = os.path.normpath(path)
		
		if system() != 'Windows':
			path = path.replace('\\', '')

		if path.lower().endswith('.pkm'):
			with open(path, 'rb') as f:
				pkm = f.read()
			# Adding extra 100 bytes of party data
			if len(pkm) != 236 and len(pkm) != 136:
				print 'Invalid filesize.'
				return
			if len(pkm) == 136:
				print 'PC-Boxed Pokemon! Adding party data...',
				pkm = makeparty(pkm)
				print 'done.'
			#handle shiny tid/sid
			if pkmisshiny:
				shinytid,shinysid = pkmrand.shinygen(pkm[0x00:0x03])
				pkm[0x0C:0x0D]=shinytid
				pkm[0x0E:0x0F]=shinysid
			print 'Encoding!'
			bin = encode(pkm)
		elif path.lower().endswith('.3gpkm'):
			print 'Converting GBA file to NDS format...',
			with open(path, 'rb') as f:
				pkm = f.read()

			if len(pkm) != 80 and len(pkm) != 100:
				print 'Invalid filesize.'
				return
			pkm = makends(pkm)
			print 'done.'
			if pkmisshiny:
				shinytid,shinysid = pkmrand.shinygen(pkm[0x00:0x03])
				pkm[0x0C:0x0D]=shinytid
				pkm[0x0E:0x0F]=shinysid

			print 'Encoding!'
			bin = encode(pkm)
		else:
			print 'Filename must end in .pkm or .3gpkm'
			return

		# Adding GTS data to end of file
		
		bin += pkm[0x08:0x0a] # id
		if ord(pkm[0x40]) & 0x04: bin += '\x03' # Gender
		else: bin += chr((ord(pkm[0x40]) & 2) + 1)
		bin += pkm[0x8c] # Level
		bin += '\x01\x00\x03\x00\x00\x00\x00\x00' # Requesting bulba, either, any
		bin += '\x00' * 20 # Timestamps and PID
		bin += pkm[0x68:0x78] # OT Name
		bin += pkm[0x0c:0x0e] # OT ID
		bin += '\xDB\x02' # Country, City
		bin += '\x46\x00\x07\x02' # Sprite, Exchanged (?), Version, Lang

		sent = False
		delete = False
		print 'Ready to send; you can now enter the GTS...'
		while not sent:
			sock, req = getReq()
			a = req.action
			if len(req.getvars) == 1:
				sendResp(sock, token)
			elif a == 'info':
				sendResp(sock, '\x01\x00')
				print 'Connection Established.'
			elif a == 'setProfile': sendResp(sock, '\x00' * 8)
			elif a == 'post': sendResp(sock, '\x0c\x00')
			elif a == 'search': sendResp(sock, '')
			elif a == 'result': sendResp(sock, bin)
			elif a == 'delete':
				sendResp(sock, '\x01\x00')
				sent = True

		print 'Pokemon sent successfully.',
	elif bw==True:
		#path = genpathV()
		path=""
		path = os.path.normpath(path)
		if system() != 'Windows':
			path = path.replace('\\', '')

		if path.startswith('"') or path.startswith("'"):
			path = path[1:]
		if path.endswith('"') or path.endswith("'"):
			path = path[:-1]
		if path.lower().endswith('.pkm'):
			with open(path, 'rb') as f:
				pkm = f.read()

			# Adding extra 100 bytes of party data
			if len(pkm) != 220 and len(pkm) != 136:
				print 'Invalid filesize: %d bytes.' % len(pkm)
				return
			if len(pkm) == 136:
				print 'PC-Boxed Pokemon! Adding party data...',
				pkm = makeparty(pkm)
				print 'done.'
			if pkmisshiny:
				shinytid,shinysid = pkmrand.shinygen(pkm[0x00:0x03])
				pkm[0x0C:0x0D]=shinytid
				pkm[0x0E:0x0F]=shinysid

			print 'Encoding!'
			bin = encode(pkm)

	###
	# Support for .3gpkm files. Currently unfinished.
	###

	#   elif path.lower().endswith('.3gpkm'):
	#       print 'Converting GBA file to NDS format...',
	#       with open(path, 'rb') as f:
	#           pkm = f.read()
	#
	#       if len(pkm) != 80 and len(pkm) != 100:
	#           print 'Invalid filesize.'
	#           return
	#       pkm = makends(pkm)
	#       print 'done.'
	#
	#       print 'Encoding!'
	#       bin = encode(pkm)

	###
	#
	###

		else:
			print 'Filename must end in .pkm'
			return

		# Adding GTS data to end of file
		bin += '\x00' * 16
		bin += pkm[0x08:0x0a] # id
		if ord(pkm[0x40]) & 0x04: bin += '\x03' # Gender
		else: bin += chr((ord(pkm[0x40]) & 2) + 1)
		bin += pkm[0x8c] # Level
		bin += '\x01\x00\x03\x00\x00\x00\x00\x00' # Requesting bulba, either, any
		bin += '\xdb\x07\x03\x0a\x00\x00\x00\x00' # Date deposited (10 Mar 2011)
		bin += '\xdb\x07\x03\x16\x01\x30\x00\x00' # Date traded (?)
		bin += pkm[0x00:0x04] # PID
		bin += pkm[0x0c:0x0e] # OT ID
		bin += pkm[0x0e:0x10] # OT Secret ID
		bin += pkm[0x68:0x78] # OT Name
		bin += '\xDB\x02' # Country, City
		bin += '\x46\x01\x15\x02' # Sprite, Exchanged (?), Version, Lang
		bin += '\x01\x00' # Unknown

		sent = False
		response = ''

		print 'Ready to send; you can now enter the GTS...'
		while not sent:
			sock, req = getReq()
			a = req.action
			if len(req.getvars) == 1:
				sendResp(sock, gtsvar.token)
				continue
			elif a == 'info':
				response = '\x01\x00'
				print 'Connection Established.'
			elif a == 'setProfile': response = '\x00' * 8
			elif a == 'post': response = '\x0c\x00'
			elif a == 'search': response = '\x01\x00'
			elif a == 'result': response = bin
			elif a == 'delete':
				response = '\x01\x00'
				sent = True

			m = hashlib.sha1()
			m.update(gtsvar.salt + urlsafe_b64encode(response) + gtsvar.salt)
			response += m.hexdigest()
			sendResp(sock, response)

		print 'Pokemon sent successfully.',
	return path
